import React from 'react';
import {
  createSwitchNavigator,
  createAppContainer,
  NavigationScreenConfigProps,
} from 'react-navigation';
import {createBottomTabNavigator} from 'react-navigation-tabs';

import {createStackNavigator} from 'react-navigation-stack';
import TabBar from './TabBar';
import {colors, defaultNavigationOptions, size} from '@/config';
import Icon from 'react-native-vector-icons/AntDesign';
/** 登录页面 */
import SignIn from '../screens/signIn';
import {tabLabelIconConfig, screenRoutes} from './menu';

/* tab页的tabBarLabel配置 */
function getDefaultNavigationOptions(config: object) {
  return {
    defaultNavigationOptions: (
      props: NavigationScreenConfigProps<any, any>,
    ) => {
      const {navigation} = props;
      const {routeName} = navigation.state;
      const {label, icon} = config[routeName];
      return {
        tabBarLabel: label,
        tabBarIcon: ({
          tintColor,
          focused,
        }: {
          tintColor: string | null;
          focused: boolean;
        }) => (
          <Icon
            name={icon}
            size={size.px(20)}
            color={focused ? colors.primary : tintColor!}
          />
        ),
      };
    },
    tabBarOptions: {
      activeTintColor: colors.primary,
      inactiveTintColor: colors.black,
      style: {
        backgroundColor: colors.white,
      },
    },
  };
}

const homeTabComponents = {};
Object.keys(tabLabelIconConfig).forEach(
  (key) =>
    (homeTabComponents[key] =
      tabLabelIconConfig[key].component || tabLabelIconConfig[key]),
);
const HomeTab = createBottomTabNavigator(homeTabComponents, {
  ...getDefaultNavigationOptions(tabLabelIconConfig),
  initialRouteName: 'Home',
  tabBarComponent: TabBar,
});

HomeTab.navigationOptions = (props: NavigationScreenConfigProps<any, any>) => {
  const {navigation} = props;
  const {routeName} = navigation.state.routes[navigation.state.index];
  const {headerTitle} = tabLabelIconConfig[routeName];
  if (headerTitle) {
    return {
      ...defaultNavigationOptions,
      headerTitle: headerTitle,
      headerRight: null,
    };
  }
  return {
    headerShown: false,
  };
};

/** 已登录的页面栈 */
const SignedIn = createStackNavigator(
  {
    Home: HomeTab,
    ...screenRoutes,
  },
  {
    initialRouteName: 'Home',
  },
);

/** 未登录的页面栈 */
const SignedOut = createStackNavigator({
  SignIn: {
    screen: SignIn,
  },
});

export const createRootNavigator = (signedIn = false) =>
  createAppContainer(
    createSwitchNavigator(
      {
        SignedIn: {
          screen: SignedIn,
        },
        SignedOut: {
          screen: SignedOut,
        },
      },
      {
        initialRouteName: signedIn ? 'SignedIn' : 'SignedOut',
        resetOnBlur: true, // 切换离开屏幕时，重置所有嵌套导航器的状态
      },
    ),
  );
